﻿using System.Linq;

using VirtualTournaments.DataAccess.SqlServer.DataProxies;

namespace VirtualTournaments.DataAccess.SqlServer.DataMappers
{
	internal sealed class TeamsDataMapper : AbstractDataMapper<SqlServer.Team, Business.Tournaments.Team, DataProxies.TeamDataProxy>
	{
		#region Singleton implementation

		private static TeamsDataMapper _instance = null;
		private static object _instanceLocker = new object();

		private TeamsDataMapper() { }

		public static TeamsDataMapper Instance
		{
			get
			{
				if (_instance == null)
				{
					lock (_instanceLocker)
					{
						if (_instance == null)
						{
							_instance = new TeamsDataMapper();
						}
					}
				}
				return _instance;
			}
		}

		#endregion

		internal override VirtualTournamentsDataContext GetDataContext()
		{
			return VirtualTournamentsDataContext.Instance;
		}

		internal override System.Data.Linq.Table<SqlServer.Team> GetDataTable()
		{
			return GetDataContext().Teams;
		}

		internal override Business.Tournaments.Team DataObject2BusinessObject(SqlServer.Team dataObject)
		{
			return new TeamDataProxy(dataObject);
		}

		internal override void BusinessObject2DataObject(Business.Tournaments.Team bizTeam, SqlServer.Team dataTeam)
		{
			dataTeam.Name = bizTeam.Name;
			dataTeam.Players.Clear();
			if (bizTeam.Players != null && bizTeam.Players.Count() > 0)
			{
				foreach (Business.Players.Player bizPlayer in bizTeam.Players)
				{
					SqlServer.Player dataPlayer = PlayersDataMapper.Instance.GetOneAsDataObject(player => player.FirstName == bizPlayer.Name.FirstName && player.Surname == bizPlayer.Name.Surname);
					if (dataPlayer == null)
						dataPlayer = PlayersDataMapper.Instance.BusinessObject2DataObject(bizPlayer);
					dataTeam.Players.Add(dataPlayer);
				}
			}
		}

		internal override void DataProxy2DataObject(TeamDataProxy proxyTeam, SqlServer.Team dataTeam)
		{
			//TODO: untested
			dataTeam.Name = proxyTeam.Name;
			if (proxyTeam.PlayersHasBeenRead)
			{
				dataTeam.Players.Clear();
				foreach (Business.Players.Player bizPlayer in proxyTeam.Players)
				{
					SqlServer.Player dataPlayer = PlayersDataMapper.Instance.GetOneAsDataObject(player => player.FirstName == bizPlayer.Name.FirstName && player.Surname == bizPlayer.Name.Surname);
					if (dataPlayer == null)
						dataPlayer = PlayersDataMapper.Instance.BusinessObject2DataObject(bizPlayer);
					dataTeam.Players.Add(dataPlayer);
				}
			}
		}
	}
}
